package controller

import (
	"my_crud_project/service"
	"strconv"
)

type PageData struct {
	Code int64       `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func QueryPageInfo(topicIdStr string) *PageData {
	topicId, err := strconv.ParseInt(topicIdStr, 10, 64)
	if err != nil {
		return &PageData{
			Data: nil,
			Code: 400,
			Msg:  "failed to convert " + topicIdStr + " to int",
		}
	}
	pageInfo, err := service.QueryPageInfo(topicId)
	if err != nil {
		return &PageData{
			Data: nil,
			Code: 400,
			Msg:  "failed to query page info at topic id:" + topicIdStr,
		}
	}
	return &PageData{
		Data: pageInfo,
		Code: 200,
		Msg:  "query success!",
	}
}

func PublishPost(topicIdStr, userIdStr, content string) *PageData {
	topicId, err := strconv.ParseInt(topicIdStr, 10, 64)
	if err != nil {
		return &PageData{
			Code: 400,
			Msg:  "failed to convert topicIdStr to int",
			Data: nil,
		}
	}
	userId, err := strconv.ParseInt(userIdStr, 10, 64)
	if err != nil {
		return &PageData{
			Code: 400,
			Msg:  "failed to convert userIdStr to int",
			Data: nil,
		}
	}
	_, err = service.PublishPost(topicId, userId, content)
	if err != nil {
		return &PageData{
			Code: 400,
			Msg:  "failed to save post",
			Data: nil,
		}
	}
	return &PageData{
		Code: 200,
		Msg:  "post success!",
		Data: nil,
	}

}
